<script setup lang="ts">
import { ElIcon } from 'element-plus'
import * as Icons from '@element-plus/icons-vue'

// 定义组件属性
const props = defineProps({
  icon: {
    type: String,
    default: 'home'
  },
  color: {
    type: String,
    default: 'currentColor'
  },
  size: {
    type: Number,
    default: 20
  },
  hoverColor: {
    type: String,
    default: 'currentColor'
  }
})

// 获取图标组件
const GetIconComponent = (iconName: string) => {
  if (!iconName) return Icons.Box

  // 将图标名称转换为PascalCase格式
  const convertToPascalCase = (iconName: string) => {
    if (!iconName) return ''
    return iconName
      .split('_')
      .map(word => word.charAt(0).toUpperCase() + word.slice(1))
      .join('')
  }

  const pascalCaseName = convertToPascalCase(iconName)

  // 尝试从Icons对象中获取图标组件
  const iconComponent = Icons[pascalCaseName as keyof typeof Icons]

  // 如果找到图标组件，则返回它
  if (iconComponent) {
    return iconComponent
  }

  return Icons.Box
}

// 获取图标状态
const getIconStatus = (iconName: string) => {
  // 检查是否为图片URL路径
  const isImagePath = iconName.startsWith('/') ||
    iconName.startsWith('../') ||
    iconName.startsWith('./') ||
    iconName.startsWith('http://') ||
    iconName.startsWith('https://') ||
    iconName.includes('.png') ||
    iconName.includes('.svg') ||
    iconName.includes('.jpg') ||
    iconName.includes('.jpeg')

  if (isImagePath) {
    return 'Image'
  } else {
    // 检查图标是否存在
    const component = GetIconComponent(iconName)
    return component ? 'Found' : 'NotFound'
  }
}
</script>


<template>
  <!-- 图片类型使用原生img标签 -->
  <img 
    v-if="icon && getIconStatus(icon) === 'Image'" 
    :src="icon" 
    class="icon-image" 
    :style="{
      width: `${size}px`,
      height: `${size}px`,
      filter: color !== 'currentColor' ? `drop-shadow(0 0 0 ${color})` : 'none'
    }"
    :class="{ 'icon-hoverable': hoverColor !== 'currentColor' }"
    alt="icon" 
  />
  <!-- 非图片类型使用ElIcon组件 -->
  <el-icon 
    v-else-if="icon" 
    :size="size" 
    :style="{
      color: color,
      cursor: hoverColor !== 'currentColor' ? 'pointer' : 'default'
    }"
    :class="{ 'icon-hoverable': hoverColor !== 'currentColor' }"
  >
    <component :is="GetIconComponent(icon || '')" />
  </el-icon>
</template>

<style scoped>
.icon-image {
  object-fit: contain;
  vertical-align: middle;
  transition: filter 0.3s ease;
}

.el-icon {
  transition: color 0.3s ease;
}

/* 悬停效果 */
.icon-hoverable:hover {
  filter: drop-shadow(0 0 0 var(--hover-color)) !important;
  color: var(--hover-color) !important;
}

/* 使用CSS变量传递hoverColor值 */
:deep(.el-icon.icon-hoverable) {
  --hover-color: v-bind(hoverColor);
}

.icon-image.icon-hoverable {
  --hover-color: v-bind(hoverColor);
}
</style>